//
//  MapViewController.m
//  mapTest
//
//  Created by xiangzhigang on 16/5/23.
//  Copyright © 2016年 xiangzhi gang. All rights reserved.
//

#import "MapViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "XZGMapTableViewController.h"

#import "XZGMap.h"

#define KSearchAreaMeters 100

@interface MapViewController () <CLLocationManagerDelegate, MKMapViewDelegate>
{
    MKCoordinateRegion currentRegion;
    CLLocationCoordinate2D coordinate;
}
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) CLGeocoder *geocoder;
@property (nonatomic,strong) NSMutableArray *nearbyInfoArray;

@end

@implementation MapViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索附近医院";
    self.view.backgroundColor = [UIColor whiteColor];
    [self configNavigation];
    [self locationManager];
    [self requestLocationAutoorize];
    
    
    [self GetCurrentLocation];
    [self geocoder];
    [self.view addSubview:self.mapView];
}

- (void)dealloc {
    NSLog(@"我被干死了");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"内存警告");
}



#pragma mark - Private
- (void)configNavigation {
    UIButton *topSearchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    topSearchButton.frame = CGRectMake(0, 0, 50, 50);
    [topSearchButton setTitle:@"列表" forState:UIControlStateNormal];
    [topSearchButton addTarget:self action:@selector(searchNearbyShopAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:topSearchButton];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    UIButton *topSearchButton1 = [UIButton buttonWithType:UIButtonTypeSystem];
    topSearchButton1.frame = CGRectMake(0, 0, 50, 50);
    [topSearchButton1 setTitle:@"返回" forState:UIControlStateNormal];
    [topSearchButton1 addTarget:self action:@selector(clickBut) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem1 = [[UIBarButtonItem alloc] initWithCustomView:topSearchButton1];
    self.navigationItem.leftBarButtonItem = rightButtonItem1;
}

- (void)requestLocationAutoorize {
    CGFloat systemVersion = [[UIDevice currentDevice].systemVersion floatValue];
    if (systemVersion >= 8) {
        [_locationManager requestAlwaysAuthorization];
    }
}
- (void)GetCurrentLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务已开启");
        [_locationManager requestAlwaysAuthorization];
        [_locationManager startUpdatingLocation];
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
    } else {
        NSLog(@"定位功能不能开启");
    }
}

- (void)clickBut {

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchNearbyShopWithRegion: (MKCoordinateRegion )region {
    // 获得附近的信息
    self.nearbyInfoArray = [NSMutableArray array];
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.region = region;
    request.naturalLanguageQuery = @"hospital";
    MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
    [localSearch startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            [self.nearbyInfoArray addObjectsFromArray:response.mapItems];
            for (MKMapItem *item in _nearbyInfoArray) {
                coordinate = item.placemark.coordinate;
                
              //  NSLog(@"%lf,%lf",coordinate.latitude,coordinate.longitude);
                
            }
            XZGMapTableViewController *xz = [[XZGMapTableViewController alloc] init];
            
            xz.coordinate1 = coordinate;
            
            xz.mapArr = self.nearbyInfoArray;
            
            [self.navigationController pushViewController:xz animated:YES];
            
        
        }else {
            NSLog(@"搜索错误, %@",error);
        }
    }];
}
#pragma mark - IBActions
- (void)searchNearbyShopAction: (UIButton *)searchButton {
    NSLog(@"重新搜索附近医院");
    if (currentRegion.span.latitudeDelta == 0.0) {
        return;
    }else {
        [self searchNearbyShopWithRegion:currentRegion];
    }
}

#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    [self.geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
    CLPlacemark *placeMark = [placemarks firstObject];
//    NSLog(@"获取地理位置成功 name = %@, locality = %@",placeMark.name,placeMark.locality);
        userLocation.title = placeMark.name;
        userLocation.subtitle = placeMark.locality;
}];
    // 当前位置显示到地图
    CLLocationCoordinate2D center = userLocation.location.coordinate;
    MKCoordinateSpan span = MKCoordinateSpanMake(0.009310, 0.007812);
    MKCoordinateRegion region = MKCoordinateRegionMake(center, span);
    MKCoordinateRegion searchRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, KSearchAreaMeters,KSearchAreaMeters);
    currentRegion  = searchRegion;
    [self.mapView setRegion:region animated:YES];
}

//- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
//    
//    [self.mapView removeFromSuperview];
//    
//    [self.view addSubview:mapView];
//}


- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}
- (MKMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
        _mapView.mapType = MKMapTypeStandard;
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        _mapView.delegate = self;
    }
    return _mapView;
}
- (CLGeocoder *)geocoder {
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }    return _geocoder;
}
@end
